<script lang="ts" setup>
///////////////////////////////////////////wangeditor//////////////////////////////////////////////////////
// 引入编辑器
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar} from '@wangeditor/editor-for-vue'
import { IToolbarConfig,Boot } from '@wangeditor/editor'
import { onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
import { appWindow } from '@tauri-apps/api/window'
import { uuid } from '../function'

appWindow.setDecorations(false);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 模式
const mode = ref<string>('default'); // 或 'simple' 'default'
// 内容html
const valueHtml = ref<string>('')
const editorConfig = { placeholder: '请输入内容...'}
// 工具栏配置 
const toolbarConfig:Partial<IToolbarConfig> = {}
// 工具栏天界配置
toolbarConfig.toolbarKeys = [
    'bold','numberedList','underline','italic','through','upimage','codeBlock','todo'
]

// toolbarConfig.insertKeys = {
//     index: 10, // 插入的位置，基于当前的 toolbarKeys
//     keys: ['menu1Conf']
// }
// 工具栏排除的配置
// toolbarConfig.excludeKeys = [
//     'fullScreen','insertVideo','bgColor','insertTable','header1','header2','header3','blockquote','undo','redo','justifyRight','justifyLeft','justifyCenter','insertLink','clearStyle','color','bulletedList',
// ]
// 编辑区实例 
const handleCreated = (editor:any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

///////////////////////////////////////////wangeditor//////////////////////////////////////////////////////
// store notes
import { notes } from '../store'
const notesStore = notes()
// 笔记noteid 同时也是窗口的 label
const noteid = ref<string>()
const time = ref<any>()

// 笔记保存方法  onChange事件触发
const savenote = function(){
    console.log('save')
    clearTimeout(time.value)
    // tauri 的剪贴板只有文本剪贴板
    time.value = setTimeout(async function(){
        // 获取编辑的内容
        notesStore.notes = JSON.parse(localStorage.getItem('notes') as string).notes
        notesStore.note.htmltext = valueHtml.value;
        notesStore.notes.filter((item,index)=>{
            if(item.noteid == noteid.value){
                notesStore.notes[index].htmltext = valueHtml.value
                notesStore.notes[index].color = notesStore.note.color
            }
        })

        // 判断内容是否为空
        if((!editorRef.value.getText()) && valueHtml.value === '<p><br></p>'  ){
            console.log(notesStore.isnull,'in')
            notesStore.isnull = true;
        }else{
            notesStore.isnull = false
        }
    },100)
}

// 初始化笔记
onMounted(async ()=>{
    // 初始化noteid
    console.log(appWindow.label)
    noteid.value = appWindow.label

    // 获取已有笔记的内容 初始化内容、颜色等
    notesStore.notes = JSON.parse(localStorage.getItem('notes') as string).notes
    let boolarr = notesStore.notes.filter((item,index)=>{
        notesStore.note = {...notesStore.notes[index]}
        if(item.noteid == noteid.value){
            return true
        }else{
            return false;
        }
    })

    //如果localstorage找不到笔记则初始化笔记到pinia
    if(boolarr.length == 0){
        let thisnote = {
            htmltext:valueHtml.value,
            noteid:noteid.value,
            title:'',
            time:'',
            color:'#A1EF9B'
        }
        notesStore.notes.push(thisnote)
        notesStore.note = thisnote;
        setTimeout(function(){
            let doc = document.getElementsByTagName('body')[0];
            doc.style.background = '#A1EF9B';
            let tool:any = document.getElementsByClassName('w-e-toolbar')[0];
            tool.style.background ='#A1EF9B';
            let text:any = document.getElementById('w-e-textarea-1');
            text.style.background ='#A1EF9B';

            // let app = document.getElementById("app");
            // app.style.background = "transparent"
            // app.style.opacity = 0.5
            // let doc = document.getElementsByTagName('body')[0];
            // doc.style.background = 'transparent';
            // let tool:any = document.getElementsByClassName('w-e-toolbar')[0];
            // tool.style.background ='transparent';
            // let text:any = document.getElementById('w-e-textarea-1');
            // text.style.background ='transparent';
        },1)
    }else{
        setTimeout(function(){
            valueHtml.value = boolarr[0].htmltext;
            let doc = document.getElementsByTagName('body')[0];
            doc.style.background = boolarr[0].color || '#A1EF9B';
            let tool:any = document.getElementsByClassName('w-e-toolbar')[0];
            tool.style.background = boolarr[0].color || '#A1EF9B';
            let text:any = document.getElementById('w-e-textarea-1');
            text.style.background = boolarr[0].color || '#A1EF9B';
        },1)
    }

    // 查看编辑器配置
    // setTimeout(function(){
    //     console.log( editorRef.value.getConfig())
    // },1)

    //文件拖拽监听
    await filedrop()

    let unlisten2 = await appWindow.listen<string>("tauri://focus",()=>{
        notesStore.show = true
        notesStore.notes = JSON.parse(localStorage.getItem('notes') as string).notes
    })
    const unlisten3 = await appWindow.listen<string>("tauri://blur",()=>{
        notesStore.show = false
    })
    // 剪贴板
    window.addEventListener('paste',clipboard)
}) 

import {writeBinaryFile,BaseDirectory,createDir} from '@tauri-apps/api/fs' 
import { appDataDir } from '@tauri-apps/api/path';
const clipboard=async function(){
    let clipboardItems =await navigator.clipboard.read();
    for(const clipboardItem of clipboardItems){
        for(const type of clipboardItem.types){
            console.log(type)
            if(type.indexOf('image')===0){
                // 文件名称
                let name = uuid()+'.'+(type.split('/')[1])
                // 剪贴板文件类型
                const blob = await clipboardItem.getType(type);
                // // 创建文件缓存文件夹  app.vue已经创建了
                // await createDir('Notes',{dir:BaseDirectory.AppData, recursive: true})
                // blob转uint8array
                let blobuint8:any
                await blob.arrayBuffer().then(async (res)=>{
                    blobuint8 = [...new Uint8Array(res)]
                })
                // 创建文件
                await writeBinaryFile(name,blobuint8, { dir: BaseDirectory.AppData });
                const appDataDirPath = await appDataDir();
                let src = convertFileSrc(appDataDirPath+name)
                imgsrc.value.push(src);
                // 触发图片上传按钮
                let button:any = document.getElementsByClassName('w-e-menu-tooltip-v5')[5];
                button.click();
            }
        }
    }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value 
    if (editor == null) return 
    editor.destroy() 
})

///////////////////////////////////////////////////////////////

// 文件拖拽监听
import { basename} from '@tauri-apps/api/path';
import { convertFileSrc } from '@tauri-apps/api/tauri';
import { open } from '@tauri-apps/api/dialog';
const filedrop = async function(){
    const unlisten = await appWindow.listen<string>("tauri://file-drop",async ({payload,windowLabel}) => {
        console.log(payload,windowLabel);
        if(windowLabel == appWindow.label) {
            for(let i = 0 ;i<payload.length;i++){
                // 判断是否是合法的图片格式，若不是则跳出此次循环
                let name = await basename(payload[i]);
                let arr = name.split('.');
                let ext = arr[arr.length-1];
                console.log(arr[arr.length-1]);
                let extarr = ['png','jpg','jpeg','gif','bmp','svg','apng','webp'];
                let boolarr = extarr.filter((item)=>{
                    return ext === item
                });
                if(boolarr.length==0) {
                    continue;
                };
                let src = convertFileSrc(payload[i])
                imgsrc.value.push(src);
                // 触发图片上传按钮
                let button:any = document.getElementsByClassName('w-e-menu-tooltip-v5')[5];
                button.click();
            }
        }
    });
}
const imgsrc = ref<string[]>([]);
// 注册自定义tool按钮

import { IButtonMenu, IDomEditor } from '@wangeditor/editor'
import { app } from '@tauri-apps/api'
class upButtonMenu implements IButtonMenu {   // TS 语法
    title:string
    tag:string
    iconSvg:string
    constructor() {
        this.title = '图片' // 自定义菜单标题
        this.iconSvg = '<svg viewBox="0 0 1024 1024"><path d="M828.708571 585.045333a48.761905 48.761905 0 0 0-48.737523 48.761905v18.529524l-72.143238-72.167619a135.972571 135.972571 0 0 0-191.585524 0l-34.133334 34.133333-120.880762-120.953905a138.898286 138.898286 0 0 0-191.585523 0l-72.167619 72.167619V292.400762a48.786286 48.786286 0 0 1 48.761904-48.761905h341.23581a48.737524 48.737524 0 0 0 34.474667-83.285333 48.737524 48.737524 0 0 0-34.474667-14.287238H146.236952A146.212571 146.212571 0 0 0 0 292.400762v585.289143A146.358857 146.358857 0 0 0 146.236952 1024h584.996572a146.212571 146.212571 0 0 0 146.236952-146.310095V633.807238a48.786286 48.786286 0 0 0-48.761905-48.761905zM146.261333 926.45181a48.737524 48.737524 0 0 1-48.761904-48.761905v-174.128762l141.409523-141.458286a38.497524 38.497524 0 0 1 53.126096 0l154.526476 154.624 209.627428 209.724953H146.236952z m633.734096-48.761905c-0.073143 9.337905-3.145143 18.383238-8.777143 25.843809l-219.843048-220.94019 34.133333-34.133334a37.546667 37.546667 0 0 1 53.613715 0l140.873143 141.897143V877.714286zM1009.615238 160.231619L863.329524 13.897143a48.737524 48.737524 0 0 0-16.091429-10.24c-11.849143-4.87619-25.161143-4.87619-37.059047 0a48.761905 48.761905 0 0 0-16.067048 10.24l-146.236952 146.334476a49.005714 49.005714 0 0 0 69.217523 69.241905l62.902858-63.390476v272.627809a48.761905 48.761905 0 1 0 97.475047 0V166.083048l62.902857 63.390476a48.737524 48.737524 0 0 0 69.217524 0 48.761905 48.761905 0 0 0 0-69.241905z"></path></svg>'
        this.tag = 'button'
    }

    // 获取菜单执行时的 value ，用不到则返回空 字符串或 false // 插入的内容
    getValue(editor: IDomEditor): string | boolean {   // TS 语法
        if(imgsrc.value.length == 0){
            // 用户点击图片插入
            const selected = open({
                multiple: true,
                filters: [{
                    name: 'Image',
                    extensions:['png','jpg','jpeg','gif','bmp','svg','apng','webp']
                }]
            }).then((res:any)=>{
                for(let i=0;i<res.length;i++){
                    let src = convertFileSrc(res[i])
                    let img = {
                        type: 'image',
                        src:src,
                        children: [{ text: '' }],
                        style:{
                            width:'50%',
                            height:'auto'
                        }
                    }
                    editor.insertNode(img)
                }
            })
        }else{
            //  用户拖拽图片插入
            for(let i=0;i<imgsrc.value.length;i++){
                let img = {
                    type: 'image',
                    src:imgsrc.value[i],
                    children: [{ text: '' }],
                    style:{
                        width:'50%',
                        height:'auto'
                    }
                }
                editor.insertNode(img)
            }
            imgsrc.value = []
        }

        return false;
        
    }

    // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
    isActive(editor: IDomEditor): boolean {  // TS 语法
        return false
    }

    // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
    isDisabled(editor: IDomEditor): boolean {   // TS 语法
        return false
    }

    // 点击菜单时触发的函数
    exec(editor: IDomEditor, value: string | boolean) {   // TS 语法
        if (this.isDisabled(editor)) return
        if(typeof value == 'string'){
            editor.insertText(value) // value 即 this.value(editor) 的返回值
        }
    }
}
const upimage = {
  key: 'upimage', // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new upButtonMenu() // 把 `YourMenuClass` 替换为你菜单的 class
  },
}
Boot.registerMenu(upimage)

///////////////////////////////////////////////////////////////

</script>

<template>
<div :style="{background:notesStore.note.color,width:'100%',height:'100vh'}">
    <div class="editor-container" :style="{background:notesStore.note.color}">
        <Editor
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
            @onChange='savenote'
        />
    </div>
    <div class="toolbar-container" :style="{background:notesStore.note.color}">
        <Toolbar
            v-show="notesStore.gettersShow"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
    </div>
</div>
</template>
<style>
.editor-container{
    background: black;
    margin-top: 30px;
    width: 100%;
    height: calc(100vh - 70px);
}
.toolbar-container{
    width: 100%;
    height: 40px;
}

</style>